package com.csust.zerocode.langgraph4j.node;

import com.csust.zerocode.constant.AppConstant;
import com.csust.zerocode.core.AiCodeGeneratorFacade;
import com.csust.zerocode.langgraph4j.state.WorkflowContext;
import com.csust.zerocode.model.enums.CodeGenTypeEnum;
import com.csust.zerocode.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.bsc.langgraph4j.action.AsyncNodeAction;
import org.bsc.langgraph4j.prebuilt.MessagesState;
import reactor.core.publisher.Flux;

import java.time.Duration;

import static org.bsc.langgraph4j.action.AsyncNodeAction.node_async;

@Slf4j
public class CodeGeneratorNode {
    public static AsyncNodeAction<MessagesState<String>> create() {
        return node_async(state -> {
            WorkflowContext context = WorkflowContext.getContext(state);
            log.info("执行节点: 代码生成");
            //得到增强后的提示词
            String enhancedPrompt = context.getEnhancedPrompt();
            //生成类型
            CodeGenTypeEnum codeGenTypeEnum = context.getGenerationType();
            //appId
            Long appId = 1L;
            AiCodeGeneratorFacade aiCodeGeneratorFacade = SpringContextUtil.getBean(AiCodeGeneratorFacade.class);
            log.info("开始执行代码生成，生成类型:{}（{}）", codeGenTypeEnum.getValue(), codeGenTypeEnum.getText());
            Flux<String> stringFlux = aiCodeGeneratorFacade.generateAndSaveCodeStream(enhancedPrompt, codeGenTypeEnum, appId);
            String result = stringFlux.blockLast(Duration.ofMinutes(10));
            // 根据类型 设置生成目录
            String generatedCodeDir = String.format("%s/%s_%s", AppConstant.CODE_OUTPUT_ROOT_DIR, codeGenTypeEnum.getValue(), appId);
            log.info("代码生成目录: {}", generatedCodeDir);
            // 更新状态
            context.setCurrentStep("代码生成");
            context.setGeneratedCodeDir(generatedCodeDir);
            return WorkflowContext.saveContext(context);
        });
    }
}
